<template>
  <div class="exam-detail-page">
    <div class="page-header">
      <el-button @click="goBack" type="text" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
        返回考试列表
      </el-button>
      <h2>考试详情</h2>
    </div>

    <div class="exam-detail-content">
      <!-- 考试基本信息 -->
      <div class="exam-info-card">
        <div class="exam-header">
          <div class="exam-icon">
            <img :src="examDetail.icon" :alt="examDetail.name" />
          </div>
          <div class="exam-title">
            <h1>{{ examDetail.name }}</h1>
            <p>{{ examDetail.description }}</p>
            <div class="exam-tags">
              <el-tag type="info">{{ examDetail.category }}</el-tag>
              <el-tag :type="getDifficultyType(examDetail.difficulty)">
                {{ examDetail.difficulty }}
              </el-tag>
            </div>
          </div>
        </div>
        
        <div class="exam-stats">
          <div class="stat-item">
            <div class="stat-value">{{ examDetail.duration }}</div>
            <div class="stat-label">考试时长（分钟）</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ examDetail.totalQuestions }}</div>
            <div class="stat-label">题目数量</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ examDetail.passScore }}</div>
            <div class="stat-label">及格分数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ examDetail.maxAttempts || '不限' }}</div>
            <div class="stat-label">考试次数</div>
          </div>
        </div>
      </div>

      <!-- 考试说明 -->
      <div class="exam-instructions">
        <h3>考试说明</h3>
        <div class="instructions-content">
          <div v-if="examDetail.instructions" class="instruction-text">
            {{ examDetail.instructions }}
          </div>
          <div v-else class="default-instructions">
            <p>1. 请确保网络连接稳定，考试过程中请勿刷新页面</p>
            <p>2. 考试时间到后系统将自动提交试卷</p>
            <p>3. 答题过程中可以随时保存进度</p>
            <p>4. 提交后无法修改答案，请仔细检查</p>
          </div>
        </div>
      </div>

      <!-- 题目类型分布 -->
      <div class="question-types">
        <h3>题目类型分布</h3>
        <div class="types-grid">
          <div v-for="(count, type) in examDetail.questionTypes" :key="type" class="type-item">
            <div class="type-icon">
              <el-icon v-if="type === 'singleChoice'"><CircleCheck /></el-icon>
              <el-icon v-else-if="type === 'multipleChoice'"><Select /></el-icon>
              <el-icon v-else-if="type === 'trueFalse'"><Switch /></el-icon>
              <el-icon v-else-if="type === 'fillBlank'"><Edit /></el-icon>
              <el-icon v-else><QuestionFilled /></el-icon>
            </div>
            <div class="type-info">
              <div class="type-name">{{ getQuestionTypeText(type) }}</div>
              <div class="type-count">{{ count }}题</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 考试要求 -->
      <div class="exam-requirements">
        <h3>考试要求</h3>
        <div class="requirements-list">
          <div class="requirement-item">
            <el-icon><User /></el-icon>
            <span>需要登录账号</span>
          </div>
          <div class="requirement-item">
            <el-icon><Monitor /></el-icon>
            <span>支持PC端和移动端</span>
          </div>
          <div class="requirement-item">
            <el-icon><Connection /></el-icon>
            <span>需要稳定的网络连接</span>
          </div>
          <div class="requirement-item">
            <el-icon><Lock /></el-icon>
            <span>考试过程中请勿切换页面</span>
          </div>
        </div>
      </div>

      <!-- 开始考试 -->
      <div class="start-exam-section">
        <div class="start-info">
          <h3>准备开始考试</h3>
          <p>请确认您已了解考试规则和要求，准备好后点击开始考试</p>
        </div>
        <div class="start-actions">
          <el-button 
            type="primary" 
            size="large" 
            @click="startExamAction"
            :loading="starting"
            :disabled="!canStartExam"
          >
            开始考试
          </el-button>
          <el-button 
            size="large" 
            @click="previewExam"
            :disabled="!examDetail.previewEnabled"
          >
            预览题目
          </el-button>
        </div>
      </div>

      <!-- 考试记录 -->
      <div v-if="examHistory.length > 0" class="exam-history">
        <h3>考试记录</h3>
        <div class="history-list">
          <div v-for="record in examHistory" :key="record.id" class="history-item">
            <div class="history-info">
              <div class="history-date">{{ formatDate(record.startTime) }}</div>
              <div class="history-score">
                <span class="score">{{ record.score }}分</span>
                <el-tag :type="record.result === '通过' ? 'success' : 'danger'" size="small">
                  {{ record.result }}
                </el-tag>
              </div>
            </div>
            <div class="history-actions">
              <el-button type="text" size="small" @click="viewResult(record.id)">
                查看结果
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, 
  CircleCheck, 
  Select, 
  Switch, 
  Edit, 
  QuestionFilled,
  User,
  Monitor,
  Connection,
  Lock
} from '@element-plus/icons-vue'
import { getExamDetail, getExamHistory, startExam } from '@/api/system'

const router = useRouter()
const route = useRoute()

// 响应式数据
const examDetail = ref({})
const examHistory = ref([])
const starting = ref(false)
const loading = ref(false)

// 计算属性
const canStartExam = computed(() => {
  return examDetail.value.id && !starting.value
})

// 获取考试详情
const fetchExamDetail = async () => {
  const examId = route.params.id
  
  loading.value = true
  try {
    // 使用mock数据
    const mockExamDetail = {
      id: examId,
      name: '日语N5基础语法考试',
      description: '测试日语N5级别的基础语法知识，包括助词、动词变化、形容词变化等基础语法点。本考试适合日语初学者，通过考试可以证明具备基础的日语语法能力。',
      category: 'JLPT',
      difficulty: '初级',
      duration: 60,
      totalQuestions: 50,
      passScore: 60,
      maxScore: 100,
      icon: 'https://via.placeholder.com/80x80/409EFF/FFFFFF?text=N5',
      rules: [
        '考试时间为60分钟，超时自动提交',
        '考试过程中不得切换页面或打开其他应用',
        '每道题目只能提交一次答案',
        '考试结束后系统自动评分',
        '成绩达到60分以上为通过'
      ],
      questionTypes: [
        { type: 'singleChoice', name: '单选题', count: 30, score: 2 },
        { type: 'multipleChoice', name: '多选题', count: 10, score: 3 },
        { type: 'trueFalse', name: '判断题', count: 10, score: 1 }
      ],
      tags: ['语法', '基础', 'N5', 'JLPT'],
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: '2024-01-15T00:00:00Z'
    }
    
    examDetail.value = mockExamDetail
  } catch (error) {
    console.error('获取考试详情失败:', error)
    ElMessage.error('获取考试详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取考试历史
const fetchExamHistory = async () => {
  const examId = route.params.id
  try {
    // 使用mock数据
    examHistory.value = [
      {
        id: 1,
        examDate: '2024-01-15T10:00:00Z',
        score: 85,
        status: 'passed',
        duration: 45,
        totalQuestions: 50,
        correctAnswers: 42,
        wrongAnswers: 8
      },
      {
        id: 2,
        examDate: '2024-01-10T14:00:00Z',
        score: 72,
        status: 'passed',
        duration: 58,
        totalQuestions: 50,
        correctAnswers: 36,
        wrongAnswers: 14
      },
      {
        id: 3,
        examDate: '2024-01-05T09:00:00Z',
        score: 58,
        status: 'failed',
        duration: 60,
        totalQuestions: 50,
        correctAnswers: 29,
        wrongAnswers: 21
      }
    ]
  } catch (error) {
    console.error('获取考试历史失败:', error)
  }
}

// 获取难度类型
const getDifficultyType = (difficulty) => {
  switch (difficulty) {
    case '初级': return 'success'
    case '中级': return 'warning'
    case '高级': return 'danger'
    default: return 'info'
  }
}

// 获取题目类型文本
const getQuestionTypeText = (type) => {
  const typeMap = {
    'singleChoice': '单选题',
    'multipleChoice': '多选题',
    'trueFalse': '判断题',
    'fillBlank': '填空题'
  }
  return typeMap[type] || '其他类型'
}

// 格式化日期
const formatDate = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleDateString('zh-CN')
}

// 开始考试
const startExamAction = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要开始"${examDetail.value.name}"考试吗？\n考试时长：${examDetail.value.duration}分钟\n题目数量：${examDetail.value.totalQuestions}题`,
      '开始考试',
      {
        confirmButtonText: '开始考试',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    starting.value = true
    
    // 模拟考试开始成功
    ElMessage.success('考试开始成功！')
    
    // 跳转到考试页面
    router.push({
      path: '/exam-room',
      query: { 
        sessionId: `session_${Date.now()}`,
        examId: examDetail.value.id
      }
    })
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('开始考试失败:', error)
      ElMessage.error('开始考试失败，请稍后重试')
    }
  } finally {
    starting.value = false
  }
}

// 预览考试
const previewExam = () => {
  ElMessage.info('预览功能开发中')
}

// 查看考试结果
const viewResult = (resultId) => {
  router.push({
    path: '/exam-result',
    query: { resultId }
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  fetchExamDetail()
  fetchExamHistory()
})
</script>

<style scoped>
.exam-detail-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px 0;
}

.page-header {
  max-width: 1200px;
  margin: 0 auto 30px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.back-btn {
  font-size: 1rem;
  color: #666;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.8rem;
}

.exam-detail-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.exam-info-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.exam-header {
  display: flex;
  gap: 25px;
  margin-bottom: 30px;
}

.exam-icon img {
  width: 80px;
  height: 80px;
  border-radius: 12px;
  object-fit: cover;
}

.exam-title h1 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 1.8rem;
}

.exam-title p {
  margin: 0 0 15px 0;
  color: #666;
  font-size: 1rem;
  line-height: 1.6;
}

.exam-tags {
  display: flex;
  gap: 10px;
}

.exam-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 20px;
  padding-top: 25px;
  border-top: 1px solid #eee;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 2rem;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  color: #666;
  font-size: 0.9rem;
}

.exam-instructions,
.question-types,
.exam-requirements,
.start-exam-section,
.exam-history {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.exam-instructions h3,
.question-types h3,
.exam-requirements h3,
.start-exam-section h3,
.exam-history h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 1.3rem;
}

.instructions-content {
  color: #666;
  line-height: 1.6;
}

.default-instructions p {
  margin: 0 0 10px 0;
}

.types-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.type-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s;
}

.type-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.type-icon {
  font-size: 2rem;
  color: #409eff;
}

.type-name {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 5px;
}

.type-count {
  color: #666;
  font-size: 0.9rem;
}

.requirements-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.requirement-item {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #666;
}

.requirement-item .el-icon {
  color: #409eff;
}

.start-exam-section {
  text-align: center;
}

.start-info {
  margin-bottom: 25px;
}

.start-info p {
  color: #666;
  margin: 10px 0 0 0;
}

.start-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #f8f9fa;
}

.history-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.history-date {
  color: #666;
  font-size: 0.9rem;
}

.history-score {
  display: flex;
  align-items: center;
  gap: 10px;
}

.score {
  font-weight: bold;
  color: #2c3e50;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .exam-header {
    flex-direction: column;
    text-align: center;
  }
  
  .exam-stats {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .types-grid {
    grid-template-columns: 1fr;
  }
  
  .start-actions {
    flex-direction: column;
    gap: 15px;
  }
  
  .history-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .history-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
